package com.xt.utils;

import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by WangZK on 2017/2/25.
 */
public class FileUpload {

    /**
     * 获取文件的后缀名
     *
     * @param file
     * @return
     */
    public static String getSuffix(MultipartFile file) {
        return file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    }

    /**
     * 获取文件的后缀名
     *
     * @param file
     * @return
     */
    public static String getSuffix(File file) {
        return file.getName().substring(file.getName().lastIndexOf("."));
    }

    /**
     * 上传文件
     *
     * @param file
     * @param newName
     * @param folderAdd
     * @return
     */
    public static String uploadFile(MultipartFile file, String newName, String folderAdd) {

        String uploadPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "public/" + folderAdd;

        File folder = new File(uploadPath);

        if (!folder.exists()) {
            folder.mkdir();
        }
        File newFile = new File(uploadPath + newName + getSuffix(file));

        try {
            file.transferTo(newFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return folderAdd + newName + getSuffix(file);
    }

    /**
     * 修改文件名称
     *
     * @param oldPath
     * @param folderAdd
     * @param newName
     * @return
     */
    public static String updateFileName(String oldPath, String folderAdd, String newName) {
        File oldFile = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/" + oldPath);

        File newFile = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/" + folderAdd + newName + getSuffix(oldFile));

        oldFile.renameTo(newFile);

        oldFile.delete();

        return folderAdd + newName + getSuffix(oldFile);
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    public static boolean deletedFile(String fileName, String folderAdd) {
        File file = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/" + folderAdd + fileName);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 获取文件的名称，去除后缀名
     *
     * @param file
     * @return
     */
    public static String getOriginalFileName(MultipartFile file) {
        return file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
    }
}
